package com.suneee.refund.address.service.impl;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.suneee.base.util.ContextHelper;
import com.suneee.base.util.JsonUtil;
import com.suneee.context.page.Page;
import com.suneee.core.error.Assert;
import com.suneee.core.error.ErrorUtils;
import com.suneee.core.util.StringUtils;
import com.suneee.refund.address.bean.RefundAddress;
import com.suneee.refund.address.bean.RefundAddressSearchBean;
import com.suneee.refund.address.dao.RefundAddressDao;
import com.suneee.refund.address.service.RefundAddressService;
import com.suneee.resources.ProductError;
import com.suneee.shop.dao.ShopDao;
import com.suneee.shop.entity.Shop;
import com.suneee.store.service.IThirdPartyService;
import com.suneee.store.service.ThirdPartyFactory;

@Service("api-refundAddress")
public class RefundAddressServiceImpl implements RefundAddressService {

	@Autowired
	private RefundAddressDao refundAddressDao;
	@Autowired
	private ShopDao shopDao;
	
	private IThirdPartyService client = ThirdPartyFactory.getTmallClient();

	@Override
	public Page<RefundAddress> refundAddressList(RefundAddressSearchBean refundAddress) {
//		Assert.notNull(refundAddress, "请求参数");
//		Assert.notNull(refundAddress.getShopId(), "shopId");
		if(refundAddress == null)
			refundAddress = new RefundAddressSearchBean();
		refundAddress.setEnterpriseCode(ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode());
		Page<RefundAddress> refundAddressList = refundAddressDao.refundAddressList(refundAddress);
		List<RefundAddress> items = refundAddressList.getItems();
		for (RefundAddress refundAddresss : items) {
			Shop shop = shopDao.select(refundAddresss.getShopId());
			if(shop == null)
				continue;
			refundAddresss.setShopName(shop.getName());
		}
		
		return refundAddressList;
	}

	@Override
	public void addRefundAddress(RefundAddress refundAddress) {
		Assert.notNull(refundAddress.getShopId(), "店铺id");
		Assert.notNull(refundAddress.getReceiverAddress(), "省");
		Assert.notNull(refundAddress.getReceiverCity(), "市");
		Assert.notNull(refundAddress.getReceiverDistrict(), "县,区");
		Assert.notNull(refundAddress.getReceiverState(), "详细地址");
		Assert.notNull(refundAddress.getName(), "联系人名称");
		Assert.notNull(refundAddress.getPhone(), "联系人电话");
		
		//获取店铺信息
		Shop shop = shopDao.select(refundAddress.getShopId());
		if(!shop.getProxyURL().trim().toLowerCase().startsWith("http"))
		{
			throw ErrorUtils.wrap(ProductError.TMALL_REFUND_ADDRESS,"店铺天猫对接信息有误");
		}
		
		if(refundAddress.getDefaults() == null)
		{
			refundAddress.setDefaults(false);
		}

		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
		
		//若将新增的退货地址设置成默认地址,则先将该企业下默认的退货地址修改成非默认
		if(refundAddress.getDefaults())
		{
			Object [] args = {refundAddress.getShopId(),enterpriseCode};
			refundAddressDao.executeUpdate("update t_refund_address set is_default = 0 where shop_id = ? and enterprise_code = ? ", args);
		}
		//shop中保存的调用天猫公共参数JSON串转换成 Map
		Map<String, String> publicParams = JsonUtil.parse(shop.getRuleInfo());
		publicParams.put("url", shop.getProxyURL());
		List<RefundAddress> addresssList = client.insertRefundAddressInfo(publicParams, refundAddress);
		for(RefundAddress paramADS :addresssList)
		{
			paramADS.setCreatedAt(timestamp);
			paramADS.setUpdateAt(timestamp);
			// 企业编码
			paramADS.setEnterpriseCode(enterpriseCode);
			// 用户id
			paramADS.setOptUserId(ContextHelper.getCurrentLoginInfo().getAdminId());
			paramADS.setShopId(refundAddress.getShopId());
			
			RefundAddress exitsAds = refundAddressDao.select(paramADS.getId());
			if(null == exitsAds)
			{
				paramADS.setShortName(paramADS.getReceiverState());
				refundAddressDao.insert(paramADS);
			}
		}
	}

	@Override
	public void updateRefundAddress(RefundAddress refundAddress) {
		Assert.notNull(refundAddress.getShopId(), "店铺id");
		Assert.notNull(refundAddress.getReceiverState(), "省");
		Assert.notNull(refundAddress.getReceiverCity(), "市");
		Assert.notNull(refundAddress.getReceiverDistrict(), "县,区");
		Assert.notNull(refundAddress.getReceiverAddress(), "详细地址");
		Assert.notNull(refundAddress.getName(), "联系人名称");
		Assert.notNull(refundAddress.getPhone(), "联系人电话");
		Assert.notNull(refundAddress.getId(), "主键id");
		if(refundAddress.getReceiverAddress().length() < 4 || refundAddress.getReceiverAddress().length() > 60)
		{
			throw ErrorUtils.wrap(ProductError.TMALL_REFUND_ADDRESS,"区县以下的街道地址最少要4个字，最多不能超过60个字");
		}
		
		//获取店铺信息
		Shop shop = shopDao.select(refundAddress.getShopId());
		if(!shop.getProxyURL().trim().toLowerCase().startsWith("http"))
		{
			throw ErrorUtils.wrap(ProductError.TMALL_REFUND_ADDRESS,"店铺天猫对接信息有误");
		}
		//获取退货地址信息
		RefundAddress temp = refundAddressDao.select(refundAddress.getId());
		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
		if(!temp.getEnterpriseCode().equals(enterpriseCode))
		{
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_NO_ROLE);
		}
		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		refundAddress.setUpdateAt(timestamp);
		// 企业编码
		refundAddress.setEnterpriseCode(enterpriseCode);
		// 用户id
		refundAddress.setOptUserId(ContextHelper.getCurrentLoginInfo().getAdminId());
		if(refundAddress.getDefaults())
		{
			Object [] args = {refundAddress.getShopId(),enterpriseCode};
			refundAddressDao.executeUpdate("update t_refund_address set is_default = 0 where shop_id = ? and enterprise_code = ? ", args);
		}
		else
		{
			Object [] args = {refundAddress.getShopId(),enterpriseCode};
			List<RefundAddress> adsList = refundAddressDao.selectWhere(" shop_id = ? and enterprise_code = ? ", args);
			if(null != adsList && adsList.size() == 1 && adsList.get(0).getId().equals(refundAddress.getId()))
			{
				throw ErrorUtils.wrap(ProductError.TMALL_REFUND_ADDRESS,"只有一条退货地址不能取消其默认");
			}
		}
		Map<String, String> publicParams = JsonUtil.parse(shop.getRuleInfo());
		publicParams.put("url", shop.getProxyURL());
		Boolean flag = client.updateRefundAddressInfo(publicParams, refundAddress);
		if(flag)
		{
			refundAddressDao.update(refundAddress);
		}
	}

	@Override
	public void deleteRefundAddress(Long... ids)
	{
		Assert.notNull(ids, "主键id");
		try 
		{
			List<Long> idList = Arrays.asList(ids);
			for(Long longId : idList)
			{
				//获取退货地址信息
				RefundAddress temp = refundAddressDao.select(longId);
				if(idList.size() == 1 && temp.getDefaults())
				{
					throw ErrorUtils.wrap(ProductError.VIEW_REFUND_APPLY_NO,"所选为默认地址不能被删除");
				}
				
			    if(temp.getDefaults())
			    {
			    	continue;
			    }
			  //获取店铺信息
				Shop shop = shopDao.select(temp.getShopId());
				Map<String, String> publicParams = JsonUtil.parse(shop.getRuleInfo());
				publicParams.put("url", shop.getProxyURL());
				Map<String, String> bizParams = new HashMap<String,String>();
				bizParams.put("id", longId+"");
				Boolean flag = client.deleteRefundAddressInfo(publicParams, bizParams);
				if(flag)
				{
					refundAddressDao.delete(longId);
				}
			}
		}
		catch (Exception e) 
		{
			throw ErrorUtils.wrap(ProductError.VIEW_REFUND_APPLY_NO);
		}
	}

	@Override
	public void isDefault(Long id,Integer shopId) {
		Assert.notNull(id, "主键id");
		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
		RefundAddress address = refundAddressDao.select(id);
		if(address == null || !address.getEnterpriseCode().equals(enterpriseCode))
		{
			throw ErrorUtils.wrap(ProductError.ENTERPRISE_NO_ROLE);
		}
		//获取店铺信息
		Shop shop = shopDao.select(shopId);
		if(!shop.getProxyURL().trim().toLowerCase().startsWith("http"))
		{
			throw ErrorUtils.wrap(ProductError.TMALL_REFUND_ADDRESS,"店铺天猫对接信息有误");
		}
		//获取退货地址信息
		RefundAddress temp = refundAddressDao.select(id);
		temp.setDefaults(true);
		Map<String, String> publicParams = JsonUtil.parse(shop.getRuleInfo());
		publicParams.put("url", shop.getProxyURL());
		boolean flag = client.updateRefundAddressInfo(publicParams, temp);
		if(flag)
		{
			refundAddressDao.isDefaultById(id, enterpriseCode,shopId);
		}
	}

	@Override
	public RefundAddress getRefundAddressById(Long id) 
	{
		Assert.notNull(id, "主键id");
		return refundAddressDao.select(id);
	}

	@Override
	public List<RefundAddress> getEnterpriseRefundList(RefundAddressSearchBean refundAddress) 
	{
		Assert.notNull(refundAddress, "请求参数");
		Assert.notNull(refundAddress.getShopId(), "shopId");
		refundAddress.setEnterpriseCode(ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode());
		Object[] args = new Object[]{refundAddress.getEnterpriseCode(),refundAddress.getShopId()};
		List<RefundAddress> refundAddressList = refundAddressDao.selectWhere(" enterprise_code = ? and shop_id = ? ", args);
		for (RefundAddress refundAddresss : refundAddressList)
		{
			Shop shop = shopDao.select(refundAddresss.getShopId());
			if(shop == null)
			{
				continue;
			}
			refundAddresss.setShopName(shop.getName());
		}
		return refundAddressList;
	}

	@Override
	public void syncTmallAddress() 
	{
		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
		Integer adminId = ContextHelper.getCurrentLoginInfo().getAdminId();
		//获取店铺信息
		Object [] args = {enterpriseCode};
		List<Shop> shopList = shopDao.selectWhere(" enterprise_code = ? and status = 'use' and enabled = 1 ", args);
		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		
		for(Shop shop:shopList)
		{
			if(null != shop.getRuleInfo() && !StringUtils.isEmpty(shop.getProxyURL()))
			{
				if(!shop.getProxyURL().trim().toLowerCase().startsWith("http"))
				{
					continue;
				}
				Map<String, String> publicParams = JsonUtil.parse(shop.getRuleInfo());
				publicParams.put("url", shop.getProxyURL());
				List<RefundAddress> adsList = client.queryRefundAddressInfo(publicParams, null);
				for(RefundAddress ads:adsList)
				{
					if(null != ads && 0 != ads.getId() && null != ads.getId())
					{
						ads.setCreatedAt(timestamp);
						ads.setUpdateAt(timestamp);
						// 企业编码
						ads.setEnterpriseCode(enterpriseCode);
						// 用户id
						ads.setOptUserId(adminId);
						ads.setShopId(shop.getShopId());
						
						RefundAddress paramADS = refundAddressDao.select(ads.getId());
						if(null == paramADS )
						{
							if(ads.getDefaults())
							{
								Object [] args1 = {enterpriseCode,shop.getShopId()};
								refundAddressDao.executeUpdate("update t_refund_address set is_default = 0 where enterprise_code = ? and shop_id = ?", args1);
							}
							ads.setShortName(ads.getReceiverState());
							refundAddressDao.insert(ads);	
						}
						else
						{
							ads.setCompany(paramADS.getCompany());
							ads.setShortName(paramADS.getShortName());
							ads.setCreatedAt(paramADS.getCreatedAt());
							refundAddressDao.update(ads);	
						}
					}
				}
				
			}
		}
		
		
	}
}